package com.xframe.xdal.core.handler.es;


import com.xframe.xdal.core.constant.RunOpportunity;
import com.xframe.xdal.core.handler.BeanHandlerOptions;
import com.xframe.xdal.core.handler.IAfterConstruction;
import com.xframe.xdal.core.handler.IBeanInit;
import lombok.extern.log4j.Log4j2;
import org.elasticsearch.action.get.GetResponse;

/**
 * 功能描述: 基于ES的查询处理器，将RS返回成对象
 *
 * @author xufeng
 * @version 1.0
 * @date 2023-03-20
 */
@Log4j2
public class EsBeanObjectHandler<E> implements IGetResponseHandler<E>{

    /**
     * 类型 ResultHandler
     */
    private final Class<E> elementBeanType;
    /**
     * 设置的参数对象
     */
    private BeanHandlerOptions beanHandlerOptions;

    public static <E> EsBeanObjectHandler<E> create(Class<E> beanType, BeanHandlerOptions beanHandlerOptions){
        return new EsBeanObjectHandler(beanType,beanHandlerOptions);
    }

    public EsBeanObjectHandler(Class<E> beanType,BeanHandlerOptions beanHandlerOptions){
        this.elementBeanType = beanType;
        this.beanHandlerOptions = beanHandlerOptions;
    }

    @Override
    public E handle(GetResponse response) {
        try {
            if (response == null || response.getSourceAsMap() == null) {
                return null;
            }
            String json = response.getSourceAsString();
            E bean = beanHandlerOptions.toObject(json,elementBeanType);

            if(bean instanceof IAfterConstruction){
                afterConstruction(((IAfterConstruction)bean));
            }
            beanHandlerOptions.getAutoProcRuntime().autoFill(bean,beanHandlerOptions.getTableInfo(), RunOpportunity.R);
            if(bean instanceof IBeanInit){
                initBean(((IBeanInit)bean));
            }
            return bean;
        }catch (Exception exception) {
            exception.printStackTrace();
            //log.error("exception={}",exception);
            return null;
        }
    }


    protected void afterConstruction(IAfterConstruction bean){
        try{
            bean.build();
        }catch (Exception exception){
            exception.printStackTrace();
        }
    }


    protected void initBean(IBeanInit bean){
        try{
            bean.init();
        }catch (Exception exception){
            exception.printStackTrace();
        }
    }
}
